package com.elitel.frame.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.elitel.common.utils.XCommonUtils;
//import com.elitel.common.redis.RedisDbIndex;
//import com.elitel.common.redis.service.RedisCacheService;
import com.elitel.frame.base.component.RedisCacheDataBase;
import com.elitel.frame.base.service.BaseFieldaddonsService;
import com.elitel.frame.main.dao.BaseFieldaddonsMapper;
import com.elitel.frame.main.dao.ext.ExtBaseFieldaddonsMapper;
import com.elitel.frame.main.entity.BaseFieldaddons;
import com.elitel.frame.main.entity.ext.BaseFieldaddonsExt;

@Service
public class BaseFieldaddonsServiceImpl implements BaseFieldaddonsService {
	
	@Autowired
	private BaseFieldaddonsMapper baseFieldaddonsMapper;
	@Autowired
	private ExtBaseFieldaddonsMapper extBaseFieldaddonsMapper;
	@Autowired
	private RedisCacheDataBase redisCacheDataBase;


	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public int insertFieldaddons(String fieldguids, String dtconfigid) {
		int sumOfInsertAndDelete=0;
		try {
			List<BaseFieldaddons> selectBaseFieldaddons = extBaseFieldaddonsMapper.getBaseFieldaddonsBydtconfig(dtconfigid);
			List<BaseFieldaddons> newBaseFieldAdditionsList = new ArrayList<>();
			String[] fieldGuidArray = fieldguids.split(",");

			sumOfInsertAndDelete = insertBaseFieldAddons(dtconfigid, selectBaseFieldaddons, newBaseFieldAdditionsList, fieldGuidArray);

			//删除数据
			sumOfInsertAndDelete = deleteBaseFieldAdditions(selectBaseFieldaddons, newBaseFieldAdditionsList);

		} catch (Exception e) {
			e.printStackTrace();
		}

		//更新缓存数据
		redisCacheDataBase.refreshFieldaddonsRedisCache(dtconfigid);

		return sumOfInsertAndDelete;
	}

	private int deleteBaseFieldAdditions( List<BaseFieldaddons> selectBaseFieldaddons, List<BaseFieldaddons> newBaseFieldAdditionsList) {
		int deleteCount = 0;
		List<String> fieldIdList = new ArrayList<String>();
		for (BaseFieldaddons newBaseFieldAdditions : newBaseFieldAdditionsList) {
			fieldIdList.add(newBaseFieldAdditions.getFieldid() + newBaseFieldAdditions.getAltername());
		}

		for (BaseFieldaddons selectedBaseFieldAddition : selectBaseFieldaddons) {
			if(!fieldIdList.contains(selectedBaseFieldAddition.getFieldid() + selectedBaseFieldAddition.getAltername())){
				deleteCount += baseFieldaddonsMapper.deleteByPrimaryKey(selectedBaseFieldAddition.getGuid());
			}
		}
		return deleteCount;
	}

	private int insertBaseFieldAddons(String dtconfigid,  List<BaseFieldaddons> existedBaseFieldadditionsList,
			List<BaseFieldaddons> newBaseFieldAdditionsList, String[] mixedFieldGuidArray) {

		int insertCount = 0;
		if( mixedFieldGuidArray == null)
			return insertCount;

		List<String> existedFieldIdList = new ArrayList<String>();
		if(XCommonUtils.isNotEmpty(existedBaseFieldadditionsList)){
			for (BaseFieldaddons existedBaseFieldAdditions : existedBaseFieldadditionsList) {
				existedFieldIdList.add(existedBaseFieldAdditions.getFieldid());
			}
		}

		int occurOrder = 0;
		for (String mixedFieldGuid : mixedFieldGuidArray) {
			occurOrder++; // is correct ?

			String[] fields = mixedFieldGuid.split("&");
			String fieldId = fields[0];
			String alterName = fields.length > 1 ? fields[1] : null;
			String isEnumInteger = fields.length >2 ? fields[2] : null;

			BaseFieldaddons baseFieldAdditions = createBaseFieldaddons(fieldId, alterName, isEnumInteger, dtconfigid, occurOrder);
			newBaseFieldAdditionsList.add(baseFieldAdditions);

            if(!existedFieldIdList.contains(fieldId)){
				//插入不存在的FieldGuid
				insertCount += baseFieldaddonsMapper.insertSelective(baseFieldAdditions);
			}else{
				//验证相同字段不同的主表关系字段
				if(alterName == null)
					continue;

				List<BaseFieldaddons> baseFieldAdditionsListByFieldId = extBaseFieldaddonsMapper.getBaseFieldaddonsByFieldId(fieldId,dtconfigid);
				if(XCommonUtils.isEmpty(baseFieldAdditionsListByFieldId))
					continue;

				boolean isLinkfield = true;
				for (BaseFieldaddons existedBaseFieldAdditions : baseFieldAdditionsListByFieldId) {
					if(existedBaseFieldAdditions.getAltername().equals(alterName)){
						isLinkfield = false;
					}
				}
				if(isLinkfield){
					insertCount += baseFieldaddonsMapper.insertSelective(baseFieldAdditions);
				}
			}
		}

		return insertCount;
	}


	private BaseFieldaddons createBaseFieldaddons(String fieldId, String alterName, String isEnumInteger,
												  String dtconfigid, int occurOrder){
		BaseFieldaddons baseFieldAdditions = new BaseFieldaddons();

		baseFieldAdditions.setGuid(UUID.randomUUID().toString());
        baseFieldAdditions.setFieldid(fieldId);
		baseFieldAdditions.setDtConfigId(dtconfigid);
		baseFieldAdditions.setQueryorder(occurOrder);
		baseFieldAdditions.setShoworder(occurOrder);
		baseFieldAdditions.setCreatedate(sdf.format(new Date()));

		baseFieldAdditions.setAltername(XCommonUtils.isNotEmpty(alterName) ? alterName : dtconfigid) ;
		baseFieldAdditions.setIsenum(XCommonUtils.isNotEmpty(isEnumInteger) ? Integer.valueOf(isEnumInteger) : 0);

		return baseFieldAdditions;
	}


	@Override
	public List<BaseFieldaddons> selectFieldaddonsBydtconfigid(String dtconfigid) {
		List<BaseFieldaddons> baseFieldaddonsList = new ArrayList<BaseFieldaddons>();
		try {
			baseFieldaddonsList = extBaseFieldaddonsMapper.getBaseFieldaddonsBydtconfig(dtconfigid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return baseFieldaddonsList;
	}

	@Override
	public List<BaseFieldaddonsExt> getShowFieldListForPageView(String serviceId) {
		List<BaseFieldaddonsExt> baseFieldaddonsExts = new ArrayList<BaseFieldaddonsExt>();
		try {
			baseFieldaddonsExts = extBaseFieldaddonsMapper.getShowFieldListForPageViewByServiceId(serviceId);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return baseFieldaddonsExts;
	}

	@Override
	public List<BaseFieldaddonsExt> selectExtendFieldaddonsList(String dtconfigid) {
		List<BaseFieldaddonsExt> baseFieldaddonsExts = new ArrayList<BaseFieldaddonsExt>();
		try {
			baseFieldaddonsExts = extBaseFieldaddonsMapper.getBaseFieldaddonsByPage(dtconfigid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return baseFieldaddonsExts;
	}

	@Override
	public Integer updateFieldaddons(BaseFieldaddons bf) {
		Integer result = baseFieldaddonsMapper.updateByPrimaryKeySelective(bf);
		if(result > 0){
			//更新缓存数据
			BaseFieldaddons baseFieldaddons = baseFieldaddonsMapper.selectByPrimaryKey(bf.getGuid());
			if(baseFieldaddons != null){
				if(baseFieldaddons.getDtConfigId() !=null && baseFieldaddons.getDtConfigId() !=""){
					redisCacheDataBase.refreshFieldaddonsRedisCache(baseFieldaddons.getDtConfigId());
				}
			}
		}
		return result;
	}

	@Override
	public List<BaseFieldaddonsExt> selectFieldaddonsBydtconfigidOrder(String dtconfigid) {
		List<BaseFieldaddonsExt> baseFieldaddonsExts = new ArrayList<BaseFieldaddonsExt>();
		try {
			baseFieldaddonsExts = extBaseFieldaddonsMapper.getBaseFieldaddonsByPageOrder(dtconfigid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return baseFieldaddonsExts;
	}
	
	
}
